package cn.conac.rc.ofs.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import cn.conac.rc.ofs.entity.AnalzWarningEntity;
import cn.conac.rc.ofs.entity.OrganizationEntity;
import cn.conac.rc.ofs.repository.AnalzWarningRepository;
import cn.conac.rc.ofs.repository.OrganizationRepository;

@Configuration
@EnableScheduling // 启用定时任务
public class AnalzWarningEngine {

	@Autowired
	private AnalzWarningRepository repository;
	@Autowired
	private OrganizationRepository orgRepository;

	//@Scheduled(cron = "0 0/5 9,18 * * ?") // 每20秒执行一次
	public void scheduler() {
		// 清空原数据并重新计算
		repository.deleteAll();

		Map<Integer, AnalzWarningEntity> warningMaps = new HashMap<Integer, AnalzWarningEntity>();
		List<OrganizationEntity> orgIdsWithNoDept = orgRepository.findOrgIdWithNoDeptList();
		for (OrganizationEntity orgIdObj : orgIdsWithNoDept) {
			OrganizationEntity orgId = (OrganizationEntity)orgIdObj;
			if (!warningMaps.containsKey(orgId.getId())) {
				AnalzWarningEntity entity = new AnalzWarningEntity();
				entity.setId(orgId.getId());
				entity.setAreaCode(orgId.getAreaCode());
				warningMaps.put(orgId.getId(), entity);
			}
			warningMaps.get(orgId.getId()).setWarningDept(Boolean.TRUE);
		}
		List<OrganizationEntity> orgIdsWithNoDuty = orgRepository.findOrgIdWithNoDutyList();
		for (OrganizationEntity orgIdObj : orgIdsWithNoDuty) {
			if (!warningMaps.containsKey(orgIdObj.getId())) {
				AnalzWarningEntity entity = new AnalzWarningEntity();
				entity.setId(orgIdObj.getId());
				entity.setAreaCode(orgIdObj.getAreaCode());
				warningMaps.put(orgIdObj.getId(), entity);
			}
			warningMaps.get(orgIdObj.getId()).setWarningDuty(Boolean.TRUE);
		}
		List<OrganizationEntity> orgIdsWithNoItem = orgRepository.findOrgIdWithNoItemList();
		for (OrganizationEntity orgIdObj : orgIdsWithNoItem) {
			if (!warningMaps.containsKey(orgIdObj.getId())) {
				AnalzWarningEntity entity = new AnalzWarningEntity();
				entity.setId(orgIdObj.getId());
				entity.setAreaCode(orgIdObj.getAreaCode());
				warningMaps.put(orgIdObj.getId(), entity);
			}
			warningMaps.get(orgIdObj.getId()).setWarningEmpRemarks(Boolean.TRUE);
		}
		List<OrganizationEntity> orgIdsWithNoOLName = orgRepository.findOrgIdWithNoOLNameList();
		for (OrganizationEntity orgIdObj : orgIdsWithNoOLName) {
			if (!warningMaps.containsKey(orgIdObj.getId())) {
				AnalzWarningEntity entity = new AnalzWarningEntity();
				entity.setId(orgIdObj.getId());
				entity.setAreaCode(orgIdObj.getAreaCode());
				warningMaps.put(orgIdObj.getId(), entity);
			}
			warningMaps.get(orgIdObj.getId()).setWarningOnlineName(Boolean.TRUE);
		}
		for (AnalzWarningEntity warning : warningMaps.values()) {
			repository.save(warning);
		}
	}
}
